package andy.ham;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.List;

import andy.ham.DaoMaster.DevOpenHelper;

//继承来自listView
public class LifeDiary extends ListActivity  implements
		OnItemLongClickListener,View.OnClickListener{
	// 检查密码
	private SharedPreferences textpassword = null;
	private String password = null;
	private boolean isSet = false;
	private EditText checkpass = null;
	// 检查是否第一次进入应用
	boolean isFirstIn = false;
	// 插入一条新纪录
	//public static final int MENU_ITEM_INSERT = Menu.FIRST;
	// 编辑内容
	public static final int MENU_ITEM_EDIT = Menu.FIRST + 1;
	// private static final String[] PROJECTION =
	// new String[] { DiaryColumns._ID,
	// DiaryColumns.TITLE, DiaryColumns.CREATED };
	//
	// GreenDAO使用的变量
	private SQLiteDatabase db;

	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private NoteDao noteDao;

	private Cursor cursor;
	private RelativeLayout layout;
	private Button cancle,delete;
	private MyAdapter adapter;
	private CheckBox checkBox;
	static boolean isMulselected = false;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.diary_list);
		cancle   = (Button)findViewById(R.id.cancle);
		delete   = (Button)findViewById(R.id.delete);
		layout = (RelativeLayout)findViewById(R.id.relative);
		checkBox = (CheckBox)findViewById(R.id.check);
		cancle.setOnClickListener(this);
		delete.setOnClickListener(this);
		// 初始化GreenDAO
		InitDAO();

		// 初始化List
		InitList();
	}
	public void onClick(View v){
			switch (v.getId()){
				case R.id.cancle:

					break;
				case R.id.delete:
					/*List<Long> bn = adapter.getSelectedItems();
					for(Long id : bn)
					{
						//根据id删除记录
						noteDao.deleteByKey(id);
						//刷新页面
					}
					onCreate(null);
					break;*/
			}

	}
	/*
	 * 初始化DAO
	 */
	private void InitDAO() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
				null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		noteDao = daoSession.getNoteDao();

	}

	/*
	 * 初始化List
	 */
	private void InitList() {
		String textColumn = NoteDao.Properties.Title.columnName;
		String dateColunm = NoteDao.Properties.Date.columnName;
		String orderBy = dateColunm + " COLLATE LOCALIZED DESC";
		cursor = db.query(noteDao.getTablename(), noteDao.getAllColumns(),
				null, null, null, null, orderBy);
		String[] from = {textColumn, dateColunm};
		int[] to = {R.id.text1, R.id.created};
		adapter = new MyAdapter(this,
				R.layout.diary_row, cursor, from, to,R.id.check,"_id",0);
		//注册长按事件监听器
		getListView().setOnItemLongClickListener(this);
		setListAdapter(adapter);
	}
	// 添加选择菜单
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		//menu.add(Menu.NONE, MENU_ITEM_INSERT, 0, R.string.menu_insert);
		//return true;
		MenuInflater mInflater = getMenuInflater();
		mInflater.inflate(R.menu.main,menu);
		return super.onCreateOptionsMenu(menu);
	}

	// 添加选择菜单的选择事件
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			// 插入一条数据
			case R.id.insert:
				Intent intent0 = new Intent(this, DiaryEditor.class);
				intent0.setAction(DiaryEditor.INSERT_DIARY_ACTION);
				intent0.setData(getIntent().getData());
				startActivity(intent0);
				LifeDiary.this.finish();
				cursor.requery();
				break;
			case R.id.del:
				//layout.setVisibility(View.VISIBLE);
				isMulselected = true;
				List<Long> bn = adapter.getSelectedItems();
				for(Long id : bn)
				{
					//根据id删除记录
					noteDao.deleteByKey(id);
					//刷新页面
				}
				onCreate(null);
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	//短按点击事件
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// Uri uri = ContentUris.withAppendedId(getIntent().getData(), id);
		String mid = Long.toString(id);
		Log.d("id", mid);
		// Intent intent = new Intent();
		// startActivity(new Intent(DiaryEditor.EDIT_DIARY_ACTION, uri));
		Intent intent = new Intent(this, DiaryEditor.class);
		intent.setAction(DiaryEditor.EDIT_DIARY_ACTION);
		Bundle bundle = new Bundle();
		bundle.putLong("id", id);
		intent.putExtras(bundle);
		Log.d("id", mid);
		startActivity(intent);
		LifeDiary.this.finish();
		cursor.requery();
	}
	//长按点击事件
	public boolean onItemLongClick(AdapterView parent, View view, int position,
								   final long id){
		//layout.setVisibility(View.VISIBLE);
		//Toast.makeText(this,"success",Toast.LENGTH_SHORT).show();
		Builder dialog = new AlertDialog.Builder(LifeDiary.this);
		dialog.setIcon(android.R.drawable.ic_dialog_info);
		dialog.setTitle("提示");
		dialog.setMessage("是否删除该条记录");
		dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//删除
				noteDao.deleteByKey(id);
				//刷新activity
				onCreate(null);
			}
		});
		dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				//不删除
			}
		});
		dialog.create();
		dialog.show();
		return true;
	}
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		cursor.requery();
		super.onActivityResult(requestCode, resultCode, intent);
		// renderListView();
	}
	// @SuppressWarnings("deprecation")
	// private void renderListView() {
	// Cursor cursor = managedQuery(getIntent().getData(), PROJECTION,
	// null,null, DiaryColumns.DEFAULT_SORT_ORDER);
	//
	// SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
	// R.layout.diary_row, cursor, new String[] { DiaryColumns.TITLE,
	// DiaryColumns.CREATED }, new int[] { R.id.text1,R.id.created });
	// setListAdapter(adapter);
	// }
}
